﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using ProtocoloCarSharing;

namespace AppAgenteVehiculo
{
    public class ConnectionSocket
    {
        private static Socket ConnectSocket()
        {
            IPEndPoint ipe = new IPEndPoint(Program.ipVehiculo, Program.tcpPort);
            Socket socket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            socket.Connect(ipe);

            if (!socket.Connected)
            {
                socket= null; 
            }
            
            return socket;
        }

        // This method requests the home page content for the specified server.
        public static MensajeProtocolo SocketSendReceive(MensajeProtocolo request)
        {
            Byte[] bytesSent = request.ConvertirAByte();
            Byte[] bytesReceived = new Byte[1024];
            Byte[] bytesMsg = new Byte[0];
            Byte[] bytesAux = null;

            // Create a socket connection with the specified server and port.
            Socket s;

            try
            {
                s = ConnectSocket();
            }
            catch (SocketException e)
            {
                return new MensajeProtocolo(Protocolo.Header.RES, Protocolo.Comando.SERVIDOR_FUERA_DE_SERVICIO, e.Message.Length, e.Message);
            }

            if (s == null)
                throw new Exception();

            // Send request to the server.
            s.Send(bytesSent, bytesSent.Length, 0);

            // Receive the server home page content.
            int bytes = 0;

            // The following will block until te page is transmitted.
            do
            {
                bytes = s.Receive(bytesReceived, bytesReceived.Length, 0);

                if(bytes<1024)
                {
                    bytesAux = new Byte[bytes];
                    Array.Copy(bytesReceived,bytesAux,bytes);
                    bytesMsg = bytesMsg.Concat(bytesAux).ToArray();
                }
                else
                {
                    bytesMsg = bytesMsg.Concat(bytesReceived).ToArray();
                }
            }
            while (bytes > 0);

            MensajeProtocolo msgRequest = new MensajeProtocolo(bytesMsg);

            return msgRequest;
        }
    }
}
